package com.star.caffeine.service;

import com.star.caffeine.model.UserVO;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@EqualsAndHashCode(callSuper = true)
@Service
@Data
@Slf4j
public class UserCache extends BaseCaffeineCacheConfig {
    
//    private String name = "UserCache";


    private final UserVO userVO1 = new UserVO("star", 18, "男");
    private final UserVO userVO2 = new UserVO("Lili", 16, "女");
    private final List<UserVO> userVOList = new ArrayList<>(List.of(userVO1, userVO2));

    @Override
    public Object getValue(Object key) {

        String name = (String) key;
        UserVO user = userVOList.stream()
                .filter(userVO -> userVO.getName().equals(name))
                .findFirst().orElse(null);
        return user;
    }
    
    @Cacheable(value = "caffeine",
            key = "#name",
            condition = "#name != 'weapon'")
    public UserVO getUser(String name) {
        // Do something
        log.info("查询数据库");

        UserVO user = userVOList.stream()
                .filter(userVO -> userVO.getName().equals(name))
                .findFirst().orElse(null);
        return user;
    }

    @CacheEvict(value = "caffeine",
            key = "#name",
            condition = "#name != 'weapon'")
    public void deleteUnit(String unitType, String unitId) {
        // Do something
    }

}